import modelExtend from 'dva-model-extend'
import api from 'api'
import { pageModel } from 'utils/model'
import {message} from "antd";
import {t} from "@lingui/macro";
const { pathToRegexp } = require("path-to-regexp")
const { queryCodeTableList, updateCodeTable, createCodeTable,deleteCodeTable,queryCodeTableSql,queryCodeTableExec,
  queryCodeTableTemplateGroupOptions,queryCodeTableTemplateOptions,queryCodeTableCodeFile,queryCodeTableSaveCode,
  queryCodeTableCodes, queryCodeTableDbTables, queryCodeTableSaveTables, queryCodeTableTemplateGroupBaseDirTree
  ,queryCodeTableDiffSql,queryCodeTableDetails,updateSyncTable2CodeTable } = api
/**
 *
   //相关api信息
 queryCodeTableList: `GET ${prefix}/admin/codeTable/list`,
 updateCodeTable: `PUT ${prefix}/admin/codeTable`,
 createCodeTable: `POST ${prefix}/admin/codeTable`,
 deleteCodeTable: `DELETE ${prefix}/admin/codeTable/:ids`,
 queryCodeTableDetails: `GET ${prefix}/admin/codeTable/:id`,

原始数据解析信息
name: id   capitalName: Id capitalKeyName: Id   type: long   frontType: number     frontMax: 99999999999       frontStep:      dbType: int       dbUnsigned: false       comment: null     length: 11       scale: 0     frontLength: 12     defaultValue: null       isNotNull: true     specification: int(11)     dbForeignName:      capitalForeignName:        javaForeignName:        原始数据解析信息
name: name   capitalName: Name capitalKeyName: Name   type: String   frontType: text     frontMax: null       frontStep:      dbType: text       dbUnsigned: false       comment: 表名     length: 45       scale: 0     frontLength: 45     defaultValue: null       isNotNull: false     specification: varchar(45)     dbForeignName:      capitalForeignName:        javaForeignName:        原始数据解析信息
name: title   capitalName: Title capitalKeyName: Title   type: String   frontType: text     frontMax: null       frontStep:      dbType: text       dbUnsigned: false       comment: 表标题     length: 45       scale: 0     frontLength: 45     defaultValue: null       isNotNull: false     specification: varchar(45)     dbForeignName:      capitalForeignName:        javaForeignName:        原始数据解析信息
name: comment   capitalName: Comment capitalKeyName: Comment   type: String   frontType: text     frontMax: null       frontStep:      dbType: text       dbUnsigned: false       comment: 表注释     length: 1000       scale: 0     frontLength: 1000     defaultValue: null       isNotNull: false     specification: varchar(1000)     dbForeignName:      capitalForeignName:        javaForeignName:         *
 */
export default modelExtend(pageModel, {
  namespace: 'code_table_detail',
  state: {
    options: {
      groupId: {},
      templateId: {},
      dbTables: {}
    },
    trees: {
      baseDir: null,
    },
    showSql: {
      status: false,
      sql: "",
      tableId: null,
    },
    groupList: [], //模板分组列表
    showCode: false,
    showLoadTable: false, //展示导入数据库表表单
    showBasePath: false, //是否展示基本路径选择框
    selectBasePath: null, //已经选中的生成目录
    codeNamespace: "work.soho.", //默认代码命名空间
    execResult: "",
    currentItem: {}, //当前操作行
    codeFile: {fileName: '', body: "waiting...", id: null, templateId: null}
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        const match = pathToRegexp('/code_table/:id').exec(location.pathname)
        if (match) {
          dispatch({
            type: 'queryCodeTableDetails',
            payload: {
              id: match[1]
            }
          })

          //查询group组
          dispatch({
            type: 'queryTemplateGroupOptions',
            payload: {}
          }).then((res) => {
            //请求对应首个分组的模板
            if(res.length>0) {
              //导入第一个key模板
              dispatch({
                type: "queryCodeTableTemplateByGroupId",
                payload: {groupId: res[0].value}
              })
              //更新basedir tree
              dispatch({
                type: "queryBaseDirTree",
                payload: {groupId: res[0].value}
              })
            }
          })

          dispatch({
            type: 'queryDbTable',
            payload: {}
          })

        }
      })
    },
  },

  effects: {
    //查询当前表
    *queryCodeTableDetails({payload}, {call, put}) {
      const data = yield call(queryCodeTableDetails, payload)
      if(data.success && data.code === 2000) {
        yield put({
          type: 'updateState',
          payload: {
            currentItem: data.payload
          }

        })
      }
    },
   *queryTemplateGroupOptions({payload}, {call, put}) {
     const data = yield call(queryCodeTableTemplateGroupOptions, payload)
     if(data.success) {
       yield put({type: 'queryOptions', payload: {groupId: data.payload}})
       return data.payload;
     }
   },
    //查询db表名
   *queryDbTable({payload}, {call, put}) {
      const data = yield call(queryCodeTableDbTables, payload);
      if(data.success) {
        yield put({type: 'queryOptions', payload: {dbTables: data.payload}})
      }
   },
    //保存数据结构
    *querySaveTables({payload}, {call, put}) {
      const data = yield call(queryCodeTableSaveTables, payload)
      return data;
    },
   //查询分组模板信息
   *queryCodeTableTemplateByGroupId({payload}, {call, put}) {
     const data = yield call(queryCodeTableTemplateOptions, payload)
     if(data.success) {
       yield put({type: 'queryOptions', payload: {templateId: data.payload}})
       return data.payload;
     }
   },
   *queryBaseDirTree({payload}, {call, put}) {
     const data = yield call(queryCodeTableTemplateGroupBaseDirTree, payload)
     if(data.success) {
       yield put({type: 'updateState', payload: {trees:{baseDir: data.payload}}})
       return data.payload;
     }
   },
   *querySql({payload}, {call, put}) {
     const data = yield call(queryCodeTableSql, payload)
     if(data.success) {
       yield put({type: 'updateState', payload: {showSql: {status: true, sql: data.payload, tableId: payload.id, isDiff: false, title: '创建Sql'}}})
     }
   },
   *queryDiffSql({payload}, {call, put}) {
     const data = yield call(queryCodeTableDiffSql, payload)
     if(data.success) {
       yield put({type: 'updateState', payload: {showSql: {status: true, sql: data.payload, tableId: payload.id, isDiff: true, title: '同远程差异SQL'}}})
     }
   },
   // 同步数据库表到代码表
   *updateSyncTable2CodeTable({payload}, {call, put}) {
      const data = yield call(updateSyncTable2CodeTable, payload)
      return data;
   },
   *queryExec({payload}, {call, put}) {
     const data = yield call(queryCodeTableExec, payload)
     if(data.success) {
       if(data.code == 2000) {
         return {res: t`success`}
       } else {
          return {res: data.msg}
       }
     }
   },
   //请求代码文件
   *queryCodeFile({payload}, {call, put}) {
      // const params = {templateId: payload.templateId, id: this.state.currentItem.id}
      const data = yield call(queryCodeTableCodeFile, payload)
     if(data.success) {
       if(data.payload) {
         yield put({type: 'updateState', payload: {codeFile: data.payload}})
       } else {
         yield put({type: 'updateState', payload: {codeFile: {fileName: "error", body: data.msg}}})
       }
     }
   },
   //请求保存代码到文件
   *querySaveCode({payload}, {call, put}) {
     const data = yield  call(queryCodeTableSaveCode, payload)
     if(data.success && data.code == 2000) {
       return data;
     } else {
       return {code: 5000, msg: "创建失败"}
     }
   },
   //获取模板文件代码
   *queryCodes({payload}, {call, put}) {
     const data = yield  call(queryCodeTableCodes, payload)
     if(data.success && data.code == 2000) {
       return data;
     } else {
       return {code: 5000, msg: "创建失败"}
     }
   },
   *create({ payload }, { call, put }) {
      const data = yield call(createCodeTable, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      const data = yield call(updateCodeTable, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *delete({ payload }, { select, call, put }) {
      const data = yield call(deleteCodeTable, {ids:payload})
      if (!data.success) {
        throw data
      }
    },
  },
  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
    //隐藏sql显示框
    hideSqlModal(state) {
      return { ...state, showSql: {status: false, sql: ""} }
    },
    //显示代码框
    showCode(state, {payload}) {
      return {...state, ...payload,  showCode: true}
    },
    //隐藏代码框
    hideCode(state, {payload}) {
      return {...state, ...payload, showCode: false}
    }
  },
})
